package net.siufung.core.template.freemarker;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.template.AbstractTemplate;
import net.siufung.core.utils.StringPool;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author 陈建峰
 * @since 2022/8/22 1:58 下午
 */
@Slf4j
public class FreemarkerTemplate extends AbstractTemplate {

    /**
     * 文件后缀
     */
    private final static String TEMPLATE_SUFFIX = ".ftl";

    /**
     * freemarker 配置文件
     */
    private final Configuration configuration;

    public FreemarkerTemplate(){
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(CharsetUtil.UTF_8);
        configuration.setClassForTemplateLoading(FreemarkerTemplate.class, StringPool.SLASH);
    }

    @Override
    protected void writeFile(Map<String, Object> dataModel, String templatePath, String outputFile) {
        try {
            Template template = configuration.getTemplate(templatePath);
            try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
                template.process(dataModel,
                        new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8));
            }
            if(log.isDebugEnabled()){
                log.debug("模板:" + templatePath + ";  文件:" + outputFile);
            }
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String templateFilePath(String filePath) {
        return StrUtil.concat(false, filePath, TEMPLATE_SUFFIX);
    }
}
